package com.wxy.learn.oop.response;

import com.wxy.common.exception.BusinessException;
import com.wxy.common.rsp.FailedRsp;
import com.wxy.common.rsp.Rsp;
import com.wxy.common.rsp.SucceedRsp;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * ResponseController 响应体测试控制器
 *
 * @author wxy
 * @since 2023-01-07
 */
@RestController
public class ResponseController {
    /**
     * 删除账号接口
     *
     * @param flag true: 删除成功 false: 删除失败
     * @return Rsp
     */
    @DeleteMapping("/delete")
    public Rsp delete(@RequestParam(value = "flag") Boolean flag) {
        try {
            // 返回成功的响应结果:
            /*
            {
                "result": "delete succeed"
            }
            */
            return SucceedRsp.ok(deleteAccount(flag));
        } catch (Exception e) {
            String code = "unknown exception";
            if (e instanceof BusinessException) {
                // 如果抛出的异常属于我们自定义的业务异常, 获取自定义的错误编码
                code = ((BusinessException) e).getCode();
            }

            // 返回失败的响应结果:
            /*
            {
                "code": "DeleteFailed",
                "message": "delete failed because runtimeException"
             }
             */
            return FailedRsp.failed(code, e.getMessage());
        }
    }

    private String deleteAccount(boolean flag) {
        if (flag) {
            // 如果flag为true的时候, 返回delete succeed
            return "delete succeed";
        }

        // 如果flag为false的时候, 返回错误编码和错误信息
        throw new BusinessException("DeleteFailed",
                "delete failed because runtimeException");
    }
}
